#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2023/04/05 09:27:03
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from . import crud, schemas, models
from .database import SessionLocal, engine
from fastapi.middleware.cors import CORSMiddleware

# 根据模板文件创建对应的数据表
models.Base.metadata.create_all(bind=engine)

app = FastAPI()

app.add_middleware(
    CORSMiddleware,    
    allow_origins= "http://127.0.0.1:5173/",    
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],    
)

# 设定数据库连接
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get('/')
def index():
    return {"message": "Hello World"}


# 查询书籍
@app.get("/books/", response_model=list[schemas.Books])
def get_hospital_nums(bookname:str, db:Session=Depends(get_db)):
    db_books = crud.get_books_by_name(db, bookname=bookname)    
    if not db_books:
        raise HTTPException(status_code=400, detail="当前书籍名称未查询到相匹配的书籍。")
    return db_books

# 删除书籍
@app.post("/deleteBook/{bookid}")
def delete_book(bookid:int, db:Session=Depends(get_db)):
    return crud.delete_book_by_id(db, bookId=bookid)

# 修改书籍
@app.post("/updateBook/", response_model=schemas.Books)
def update_book(book:schemas.Books, db:Session=Depends(get_db)):
    return crud.update_book_by_id(db, book=book)

# 新增书籍
@app.post("/books/", response_model=schemas.Books)
def create_book(book: schemas.BooksBase, db: Session = Depends(get_db)):
    db_book = crud.get_books_by_name(db, bookname=book.bookname)
    if db_book:
        raise HTTPException(status_code=400, detail="该书籍已经存在。")
    return crud.create_book(db=db, book=book)

